<template>
  <el-autocomplete
    :value-key="name"
    v-bind="$attrs"
    v-model="selected"
    :fetch-suggestions="querySearch"
    :trigger-on-focus="false"
  />
</template>
<script>
/**
  * 带添加功能的自动完成提示框
  * 返回选项的Id
  */
export default {
  model: {
    prop: 'selected',
    event: 'select'
  },
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    /**
     * 预置选项, 在有URL的情况下，该项无效
     */
    options: {
      type: Array,
      default: () => []
    },
    /**
      * 获取选项的URL
      */
    url: {
      type: String,
      default: null
    },
    /**
     * 选项值所在索引，默认为id
     */
    index: {
      type: String,
      default: 'id'
    }
  },
  created () {
    // this.getOptions()
  },
  computed: {
    selected: {
      get () {
        return this.value.name
      },
      set (item) {
        this.$emit('change', item[this.index])
      }
    }
  },
  methods: {
    async querySearch (qs, cb) {
      const url = this.url
      const rs = await this.$http.Post(url, { qs })
      if (rs && rs.options) {
        // 调用 callback 返回建议列表的数据
        cb(rs.options)
      }
    }
  }
}

</script>
